import datetime
from bson import ObjectId
from app.errors import ParameterError
from app.validators import BaseForm
from wtforms.fields import StringField


class NotificationSendLogListVerification(BaseForm):
    page = StringField(default=1)
    limit = StringField(default=10)
    nid = StringField()
    uid = StringField()
    domain = StringField()
    taskType = StringField()
    taskCategory = StringField()
    status = StringField()
    startTime = StringField()
    endTime = StringField()

    def validate_nid(self, value):
        if value.data:
            value.data = ObjectId(value.data)

    def validate_uid(self, value):
        if value.data:
            value.data = ObjectId(value.data)

    def validate_page(self, value):
        value.data = int(value.data)
        if value.data < 1:
            value.data = 1

    def validate_startTime(self, value):
        if value.data:
            value.data = datetime.datetime.strptime(value.data, "%Y-%m-%d %H:%M:%S")

    def validate_endTime(self, value):
        if value.data:
            value.data = datetime.datetime.strptime(value.data, "%Y-%m-%d %H:%M:%S")

    def validate_limit(self, value):
        value.data = int(value.data)
        if value.data > 200 or value.data < 1:
            value.data = 10

    def get_query_dict(self):
        query_dict = dict()

        params = self.validate_for_api()

        query_dict['page'] = params.data['page']
        query_dict['limit'] = params.data['limit']

        for key, value in params.data.items():
            if value:
                if key == 'nid':
                    query_dict['_id'] = value
                elif key == 'startTime':
                    query_dict['endTime'] = {'$gte': value}
                elif key == 'endTime':
                    query_dict['endTime'] = {'$lte': value}

        if params.data['startTime'] and params.data['endTime']:
            query_dict['$and'] = [{'endTime': {'$gte': params.data['startTime']}},
                                  {'endTime': {'$lte': params.data['endTime']}}]
            query_dict.pop('endTime')

        return query_dict
